package com._119yn.host.gst200.cansocket.handler;

import com._119yn.host.gst200.cansocket.message.Ping;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class KeepaliveHandler extends ChannelHandlerAdapter implements DefaultChannelInboundHandler, DefaultChannelOutboundHandler, Runnable {

    private ChannelHandlerContext ctx;

    private Thread keepaliveThread;

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        this.keepaliveThread = new Thread(this);
        this.keepaliveThread.setName("CAN-Socket-Keepalive");
        this.keepaliveThread.setDaemon(true);
        this.keepaliveThread.start();
        this.ctx = ctx;
        this.ctx.fireChannelRegistered();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        this.keepaliveThread.interrupt();
        this.keepaliveThread = null;
        this.ctx.fireChannelUnregistered();
        this.ctx = null;
    }

    @Override
    public void run() {
        sendKeepaliveSignalLoop();
    }

    private void sendKeepaliveSignalLoop() {
        int i = 0;
        while (true) {
            try {
                i++;
                if (i % 10 == 0) {
                    sendKeepaliveSignalProcess();
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            } catch (Exception ignored) {
            }
        }
    }

    private void sendKeepaliveSignalProcess() {
        if (ctx != null && ctx.channel() != null && ctx.channel().isActive()) {
            // 发送socket保活信号
            ctx.writeAndFlush(Ping.INSTANCE);
        }
    }
}
